Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources

In [1]:
#The new version of dataset is only available in the tfds-nightly package. 
%pip --no-cache-dir install tfds-nightly --user 
!pip install tensorflow --upgrade --user
Requirement already satisfied: tfds-nightly in /root/.local/lib/python3.7/site-packages (4.4.0.dev202110240107)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied: typing-extensions; python_version < "3.8" in /root/.local/lib/python3.7/site-packages (from tfds-nightly) (3.10.0.2)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.18.2)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Requirement already satisfied: protobuf>=3.12.2 in /root/.local/lib/python3.7/site-packages (from tfds-nightly) (3.19.0)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: importlib-resources; python_version < "3.9" in /root/.local/lib/python3.7/site-packages (from tfds-nightly) (5.3.0)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Requirement already satisfied: zipp>=3.1.0; python_version < "3.10" in /root/.local/lib/python3.7/site-packages (from importlib-resources; python_version < "3.9"->tfds-nightly) (3.6.0)
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/8f/11/97aa4f0cbc771d07faf6a413559f05565af7891dbb5cedaa066be743ea61/tensorflow-2.6.0-cp37-cp37m-manylinux2010_x86_64.whl (458.3MB)
     |█████████████████               | 242.7MB 17.4MB/s eta 0:00:13  |▎                               | 3.6MB 4.3MB/s eta 0:01:47     |▋                               | 8.9MB 4.3MB/s eta 0:01:46     |▉                               | 11.6MB 4.3MB/s eta 0:01:45     |█                               | 14.3MB 4.3MB/s eta 0:01:45     |█                               | 15.6MB 4.3MB/s eta 0:01:44     |█▏                              | 17.0MB 4.3MB/s eta 0:01:44     |█▎                              | 18.3MB 4.3MB/s eta 0:01:44     |█▋                              | 23.6MB 4.3MB/s eta 0:01:43     |█▊                              | 24.9MB 28.3MB/s eta 0:00:16     |██                              | 30.2MB 28.3MB/s eta 0:00:16     |██▎                             | 32.8MB 28.3MB/s eta 0:00:16     |██▌                             | 35.5MB 28.3MB/s eta 0:00:15     |███                             | 43.6MB 28.3MB/s eta 0:00:15     |███▏                            | 44.9MB 28.3MB/s eta 0:00:15     |███▌                            | 50.0MB 26.2MB/s eta 0:00:16     |███▊                            | 52.5MB 26.2MB/s eta 0:00:16     |███▊                            | 53.8MB 26.2MB/s eta 0:00:16     |███▉                            | 55.1MB 26.2MB/s eta 0:00:16     |████                            | 56.4MB 26.2MB/s eta 0:00:16     |████                            | 57.6MB 26.2MB/s eta 0:00:16     |████                            | 58.9MB 26.2MB/s eta 0:00:16     |████▍                           | 62.7MB 26.2MB/s eta 0:00:16     |████▋                           | 66.6MB 26.2MB/s eta 0:00:15     |████▉                           | 69.2MB 26.2MB/s eta 0:00:15     |█████▌                          | 78.2MB 27.3MB/s eta 0:00:14     |█████▊                          | 82.0MB 27.3MB/s eta 0:00:14     |█████▉                          | 83.1MB 27.3MB/s eta 0:00:14     |██████                          | 85.5MB 27.3MB/s eta 0:00:14     |██████                          | 86.8MB 27.3MB/s eta 0:00:14     |██████▏                         | 88.1MB 27.3MB/s eta 0:00:14     |██████▍                         | 90.7MB 27.3MB/s eta 0:00:14     |██████▋                         | 94.4MB 27.3MB/s eta 0:00:14     |██████▉                         | 98.3MB 27.0MB/s eta 0:00:14     |███████                         | 99.5MB 27.0MB/s eta 0:00:14     |███████                         | 100.8MB 27.0MB/s eta 0:00:14     |███████▏                        | 103.3MB 27.0MB/s eta 0:00:14     |███████▎                        | 104.6MB 27.0MB/s eta 0:00:14     |███████▍                        | 105.7MB 27.0MB/s eta 0:00:14     |███████▊                        | 110.7MB 27.0MB/s eta 0:00:13     |████████                        | 113.2MB 27.0MB/s eta 0:00:13     |████████▎                       | 118.2MB 27.0MB/s eta 0:00:13     |████████▍                       | 120.6MB 26.7MB/s eta 0:00:13     |████████▌                       | 121.9MB 26.7MB/s eta 0:00:13     |█████████                       | 128.1MB 26.7MB/s eta 0:00:13     |█████████▍                      | 134.2MB 26.7MB/s eta 0:00:13     |█████████▌                      | 135.4MB 26.7MB/s eta 0:00:13     |██████████▍                     | 148.9MB 26.9MB/s eta 0:00:12     |██████████▋                     | 152.6MB 26.9MB/s eta 0:00:12     |██████████▊                     | 153.8MB 26.9MB/s eta 0:00:12     |██████████▉                     | 155.1MB 26.9MB/s eta 0:00:12     |███████████                     | 156.3MB 26.9MB/s eta 0:00:12     |███████████                     | 158.8MB 26.9MB/s eta 0:00:12     |███████████▌                    | 164.8MB 26.9MB/s eta 0:00:11     |███████████▊                    | 168.0MB 27.3MB/s eta 0:00:11     |████████████▏                   | 173.8MB 27.3MB/s eta 0:00:11     |████████████▏                   | 175.0MB 27.3MB/s eta 0:00:11     |████████████▍                   | 177.1MB 27.3MB/s eta 0:00:11     |████████████▌                   | 178.3MB 27.3MB/s eta 0:00:11     |████████████▌                   | 179.5MB 27.3MB/s eta 0:00:11     |████████████▉                   | 183.8MB 27.3MB/s eta 0:00:11     |█████████████                   | 185.2MB 9.9MB/s eta 0:00:28     |█████████████                   | 185.9MB 9.9MB/s eta 0:00:28     |█████████████                   | 186.6MB 9.9MB/s eta 0:00:28     |█████████████▌                  | 193.2MB 9.9MB/s eta 0:00:27     |█████████████▊                  | 196.8MB 9.9MB/s eta 0:00:27     |██████████████                  | 199.2MB 9.9MB/s eta 0:00:27     |██████████████                  | 200.3MB 9.9MB/s eta 0:00:27     |██████████████                  | 201.6MB 9.9MB/s eta 0:00:26     |██████████████▏                 | 202.8MB 9.9MB/s eta 0:00:26     |██████████████▎                 | 204.0MB 9.9MB/s eta 0:00:26     |██████████████▋                 | 208.7MB 27.2MB/s eta 0:00:10     |███████████████                 | 213.5MB 27.2MB/s eta 0:00:09     |███████████████▏                | 217.2MB 27.2MB/s eta 0:00:09     |███████████████▎                | 218.5MB 27.2MB/s eta 0:00:09     |████████████████                | 229.9MB 17.4MB/s eta 0:00:14     |████████████████▍               | 234.7MB 17.4MB/s eta 0:00:13     |████████████████▌               | 235.8MB 17.4MB/s eta 0:00:13     |████████████████▌               | 237.0MB 17.4MB/s eta 0:00:13     |████████████████▉               | 240.4MB 17.4MB/s eta 0:00:13     |████████████████████████████████| 458.3MB 22kB/s s eta 0:00:01     |█████████████████               | 245.0MB 17.4MB/s eta 0:00:13     |█████████████████▎              | 247.5MB 17.4MB/s eta 0:00:13     |█████████████████▌              | 250.9MB 25.3MB/s eta 0:00:09     |█████████████████▋              | 252.1MB 25.3MB/s eta 0:00:09     |█████████████████▉              | 255.6MB 25.3MB/s eta 0:00:09     |██████████████████              | 256.7MB 25.3MB/s eta 0:00:08     |██████████████████              | 259.2MB 25.3MB/s eta 0:00:08     |██████████████████▏             | 260.4MB 25.3MB/s eta 0:00:08     |██████████████████▍             | 263.9MB 25.3MB/s eta 0:00:08     |██████████████████▋             | 266.3MB 25.3MB/s eta 0:00:08     |██████████████████▊             | 267.5MB 25.3MB/s eta 0:00:08     |██████████████████▊             | 268.6MB 25.3MB/s eta 0:00:08     |███████████████████             | 272.4MB 685kB/s eta 0:04:32     |███████████████████             | 273.6MB 685kB/s eta 0:04:30     |███████████████████▏            | 275.0MB 685kB/s eta 0:04:28     |███████████████████▎            | 276.2MB 685kB/s eta 0:04:26     |███████████████████▌            | 279.8MB 685kB/s eta 0:04:21     |████████████████████▏           | 288.1MB 685kB/s eta 0:04:09     |████████████████████▏           | 289.3MB 685kB/s eta 0:04:07     |████████████████████▌           | 292.8MB 32.8MB/s eta 0:00:06     |████████████████████▌           | 294.0MB 32.8MB/s eta 0:00:06     |████████████████████▋           | 295.2MB 32.8MB/s eta 0:00:05     |████████████████████▊           | 296.4MB 32.8MB/s eta 0:00:05     |█████████████████████           | 300.0MB 32.8MB/s eta 0:00:05     |█████████████████████           | 301.3MB 32.8MB/s eta 0:00:05     |█████████████████████▏          | 302.4MB 32.8MB/s eta 0:00:05     |█████████████████████▌          | 307.4MB 32.8MB/s eta 0:00:05     |██████████████████████          | 314.9MB 32.8MB/s eta 0:00:05     |██████████████████████▎         | 319.8MB 7.9MB/s eta 0:00:18     |██████████████████████▋         | 323.5MB 7.9MB/s eta 0:00:18     |██████████████████████▊         | 324.7MB 7.9MB/s eta 0:00:17     |██████████████████████▉         | 327.1MB 7.9MB/s eta 0:00:17     |███████████████████████▏        | 331.9MB 7.9MB/s eta 0:00:17     |███████████████████████▋        | 337.9MB 23.6MB/s eta 0:00:06     |███████████████████████▊        | 339.0MB 23.6MB/s eta 0:00:06     |████████████████████████        | 342.7MB 23.6MB/s eta 0:00:05     |█████████████████████████       | 357.4MB 23.6MB/s eta 0:00:05     |█████████████████████████▏      | 360.9MB 24.2MB/s eta 0:00:05     |█████████████████████████▎      | 362.1MB 24.2MB/s eta 0:00:04     |█████████████████████████▌      | 364.4MB 24.2MB/s eta 0:00:04     |█████████████████████████▌      | 365.7MB 24.2MB/s eta 0:00:04     |█████████████████████████▉      | 369.3MB 24.2MB/s eta 0:00:04     |██████████████████████████      | 371.7MB 24.2MB/s eta 0:00:04     |██████████████████████████▎     | 376.5MB 24.2MB/s eta 0:00:04     |██████████████████████████▌     | 378.8MB 24.2MB/s eta 0:00:04     |██████████████████████████▊     | 382.3MB 24.2MB/s eta 0:00:04 eta 0:00:02     |███████████████████████████     | 387.5MB 41.5MB/s eta 0:00:02     |███████████████████████████▏    | 388.6MB 41.5MB/s eta 0:00:02     |███████████████████████████▏    | 389.7MB 41.5MB/s eta 0:00:02     |███████████████████████████▊    | 396.4MB 41.5MB/s eta 0:00:02     |████████████████████████████    | 399.8MB 41.5MB/s eta 0:00:02     |████████████████████████████    | 400.9MB 21.6MB/s eta 0:00:03     |████████████████████████████▏   | 402.7MB 21.6MB/s eta 0:00:03     |████████████████████████████▍   | 406.1MB 21.6MB/s eta 0:00:03     |████████████████████████████▍   | 407.3MB 21.6MB/s eta 0:00:03     |████████████████████████████▊   | 411.7MB 21.6MB/s eta 0:00:03     |████████████████████████████▉   | 412.7MB 21.6MB/s eta 0:00:03     |█████████████████████████████▋  | 424.7MB 26.9MB/s eta 0:00:02     |█████████████████████████████▊  | 425.9MB 26.9MB/s eta 0:00:02     |█████████████████████████████▉  | 427.1MB 26.9MB/s eta 0:00:02     |██████████████████████████████  | 428.3MB 26.9MB/s eta 0:00:02     |██████████████████████████████▎ | 434.2MB 26.9MB/s eta 0:00:01     |██████████████████████████████▊ | 439.2MB 26.9MB/s eta 0:00:01     |██████████████████████████████▊ | 440.5MB 26.9MB/s eta 0:00:01     |███████████████████████████████ | 442.9MB 26.9MB/s eta 0:00:01     |███████████████████████████████ | 445.3MB 25.7MB/s eta 0:00:01     |███████████████████████████████▏| 446.5MB 25.7MB/s eta 0:00:01     |███████████████████████████████▍| 448.9MB 25.7MB/s eta 0:00:01     |███████████████████████████████▌| 451.3MB 25.7MB/s eta 0:00:01     |███████████████████████████████▋| 452.5MB 25.7MB/s eta 0:00:01     |███████████████████████████████▊| 453.7MB 25.7MB/s eta 0:00:01     |████████████████████████████████| 457.3MB 25.7MB/s eta 0:00:01
Collecting flatbuffers~=1.12.0
  Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Collecting clang~=5.0
  Downloading https://files.pythonhosted.org/packages/32/12/e17c1220f8ca587add2e076ebb28b6c4551fcc730e3c69a5f49679ad28e9/clang-5.0.tar.gz
Collecting six~=1.15.0
  Downloading https://files.pythonhosted.org/packages/ee/ff/48bde5c0f013094d729fe4b0316ba2a24774b3ff1c52d924a8a4cb04078a/six-1.15.0-py2.py3-none-any.whl
Collecting astunparse~=1.6.3
  Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Collecting opt-einsum~=3.3.0
  Downloading https://files.pythonhosted.org/packages/bc/19/404708a7e54ad2798907210462fd950c3442ea51acc8790f3da48d2bee8b/opt_einsum-3.3.0-py3-none-any.whl (65kB)
     |████████████████████████████████| 71kB 616kB/s  eta 0:00:01
Collecting h5py~=3.1.0
  Downloading https://files.pythonhosted.org/packages/9d/74/9eae2bedd8201ab464308f42c601a12d79727a1c87f0c867fdefb212c6cf/h5py-3.1.0-cp37-cp37m-manylinux1_x86_64.whl (4.0MB)
     |████████████████████████████████| 4.0MB 24.8MB/s eta 0:00:01     |████████▏                       | 1.0MB 24.8MB/s eta 0:00:01
Collecting keras~=2.6
  Downloading https://files.pythonhosted.org/packages/5a/38/04d9b7fb53acdf861df2c4505fa96b06c779817a511e94b8882d284ba360/keras-2.6.0-py2.py3-none-any.whl (1.3MB)
     |████████████████████████████████| 1.3MB 24.0MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: termcolor~=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Requirement already satisfied, skipping upgrade: protobuf>=3.9.2 in /root/.local/lib/python3.7/site-packages (from tensorflow) (3.19.0)
Collecting typing-extensions~=3.7.4
  Downloading https://files.pythonhosted.org/packages/60/7a/e881b5abb54db0e6e671ab088d079c57ce54e8a01a3ca443f561ccadb37e/typing_extensions-3.7.4.3-py3-none-any.whl
Collecting google-pasta~=0.2
  Downloading https://files.pythonhosted.org/packages/a3/de/c648ef6835192e6e2cc03f40b19eeda4382c49b5bafb43d88b931c4c74ac/google_pasta-0.2.0-py3-none-any.whl (57kB)
     |████████████████████████████████| 61kB 10.4MB/s eta 0:00:01
Collecting keras-preprocessing~=1.1.2
  Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 9.2MB/s  eta 0:00:01
Collecting absl-py~=0.10
  Downloading https://files.pythonhosted.org/packages/97/75/f5e61fb67ecbe45c31035b17562464e11b91a2b8a351bae5ca0db2969e3b/absl_py-0.15.0-py3-none-any.whl (132kB)
     |████████████████████████████████| 133kB 25.2MB/s eta 0:00:01
Collecting wheel~=0.35
  Downloading https://files.pythonhosted.org/packages/04/80/cad93b40262f5d09f6de82adbee452fd43cdff60830b56a74c5930f7e277/wheel-0.37.0-py2.py3-none-any.whl
Collecting numpy~=1.19.2
  Downloading https://files.pythonhosted.org/packages/08/d6/a6aaa29fea945bc6c61d11f6e0697b325ff7446de5ffd62c2fa02f627048/numpy-1.19.5-cp37-cp37m-manylinux2010_x86_64.whl (14.8MB)
     |███████████▌                    | 5.3MB 20.5MB/s eta 0:00:01     |████████████████████████████████| 14.8MB 20.5MB/s eta 0:00:01    |████████████████▋               | 7.7MB 20.5MB/s eta 0:00:01     |████████████████████████▋       | 11.4MB 20.5MB/s eta 0:00:01
Collecting grpcio<2.0,>=1.37.0
  Downloading https://files.pythonhosted.org/packages/fe/58/aa3ef8bbf78679ab431aef8a8484c3da8290a6b470dbe170000759d845da/grpcio-1.41.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.9MB)
     |████████████████████████████████| 3.9MB 16.7MB/s eta 0:00:01     |██████████████████████▋         | 2.8MB 16.7MB/s eta 0:00:01
Collecting wrapt~=1.12.1
  Downloading https://files.pythonhosted.org/packages/82/f7/e43cefbe88c5fd371f4cf0cf5eb3feccd07515af9fd6cf7dbf1d1793a797/wrapt-1.12.1.tar.gz
Collecting tensorboard~=2.6
  Downloading https://files.pythonhosted.org/packages/2d/eb/80f75ab480cfbd032442f06ec7c15ef88376c5ef7fd6f6bf2e0e03b47e31/tensorboard-2.7.0-py3-none-any.whl (5.8MB)
     |████████████████████████████████| 5.8MB 28.1MB/s eta 0:00:01     |████▋                           | 829kB 28.1MB/s eta 0:00:01     |███████████▋                    | 2.1MB 28.1MB/s eta 0:00:01     |██████████████████▉             | 3.4MB 28.1MB/s eta 0:00:01
Collecting tensorflow-estimator~=2.6
  Downloading https://files.pythonhosted.org/packages/c8/54/1b2f1e22a2670546cc02e4df1b80425edaee02133173bb91aa0f6d3d0293/tensorflow_estimator-2.6.0-py2.py3-none-any.whl (462kB)
     |████████████████████████████████| 471kB 20.8MB/s eta 0:00:01
Collecting gast==0.4.0
  Downloading https://files.pythonhosted.org/packages/b6/48/583c032b79ae5b3daa02225a675aeb673e58d2cb698e78510feceb11958c/gast-0.4.0-py3-none-any.whl
Collecting cached-property; python_version < "3.8"
  Downloading https://files.pythonhosted.org/packages/48/19/f2090f7dad41e225c7f2326e4cfe6fff49e57dedb5b53636c9551f86b069/cached_property-1.5.2-py2.py3-none-any.whl
Collecting tensorboard-data-server<0.7.0,>=0.6.0
  Downloading https://files.pythonhosted.org/packages/60/f9/802efd84988bffd9f644c03b6e66fde8e76c3aa33db4279ddd11c5d61f4b/tensorboard_data_server-0.6.1-py3-none-manylinux2010_x86_64.whl (4.9MB)
     |████████████████████████████████| 4.9MB 22.6MB/s eta 0:00:01     |███████████▌                    | 1.8MB 22.6MB/s eta 0:00:01     |████████████████████▍           | 3.1MB 22.6MB/s eta 0:00:01
Collecting google-auth<3,>=1.6.3
  Downloading https://files.pythonhosted.org/packages/83/13/9dc9121d7efca28ba3275e583262f8aff6798488fac50ae39c3099d0197d/google_auth-2.3.0-py2.py3-none-any.whl (154kB)
     |████████████████████████████████| 163kB 24.0MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (2.22.0)
Collecting google-auth-oauthlib<0.5,>=0.4.1
  Downloading https://files.pythonhosted.org/packages/b1/0e/0636cc1448a7abc444fb1b3a63655e294e0d2d49092dc3de05241be6d43c/google_auth_oauthlib-0.4.6-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: setuptools>=41.0.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (41.4.0)
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (3.1.1)
Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /opt/conda/lib/python3.7/site-packages (from tensorboard~=2.6->tensorflow) (0.16.0)
Collecting tensorboard-plugin-wit>=1.6.0
  Downloading https://files.pythonhosted.org/packages/1a/c1/499e600ba0c618b451cd9c425ae1c177249940a2086316552fee7d86c954/tensorboard_plugin_wit-1.8.0-py3-none-any.whl (781kB)
     |████████████████████████████████| 788kB 24.2MB/s eta 0:00:01     |███████████▊                    | 286kB 24.2MB/s eta 0:00:01
Collecting rsa<5,>=3.1.4
  Downloading https://files.pythonhosted.org/packages/e9/93/0c0f002031f18b53af7a6166103c02b9c0667be528944137cc954ec921b3/rsa-4.7.2-py3-none-any.whl
Collecting pyasn1-modules>=0.2.1
  Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 18.4MB/s eta 0:00:01    |██████████████▊                 | 71kB 22.6MB/s eta 0:00:01
Collecting cachetools<5.0,>=2.0.0
  Downloading https://files.pythonhosted.org/packages/ea/c1/4740af52db75e6dbdd57fc7e9478439815bbac549c1c05881be27d19a17d/cachetools-4.2.4-py3-none-any.whl
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (3.0.4)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (2019.11.28)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow) (1.24.2)
Collecting requests-oauthlib>=0.7.0
  Downloading https://files.pythonhosted.org/packages/a3/12/b92740d845ab62ea4edf04d2f4164d82532b5a0b03836d4d4e71c6f3d379/requests_oauthlib-1.3.0-py2.py3-none-any.whl
Collecting pyasn1>=0.1.3
  Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
     |████████████████████████████████| 81kB 8.4MB/s  eta 0:00:01
Collecting oauthlib>=3.0.0
  Downloading https://files.pythonhosted.org/packages/e8/5d/9dd1c29e5a786525f6342f6c1d812ed2e37edc653ad297048c1668988053/oauthlib-3.1.1-py2.py3-none-any.whl (146kB)
     |████████████████████████████████| 153kB 49.2MB/s eta 0:00:01
Building wheels for collected packages: clang, wrapt
  Building wheel for clang (setup.py) ... done
  Created wheel for clang: filename=clang-5.0-cp37-none-any.whl size=30704 sha256=fbb1b57b1e3332890f38b9ba7ef6a89e78832ea22cb326972b10434493af0602
  Stored in directory: /root/.cache/pip/wheels/a1/d0/fb/f47e814ad88e0741b0ff6fc57bc4044f61c44cb707a68de6b3
  Building wheel for wrapt (setup.py) ... done
  Created wheel for wrapt: filename=wrapt-1.12.1-cp37-cp37m-linux_x86_64.whl size=70979 sha256=74dc308512c03e4694767447ce32e36a7bf930a1ccd554a7bd75927e7c3a6ccf
  Stored in directory: /root/.cache/pip/wheels/b1/c2/ed/d62208260edbd3fa7156545c00ef966f45f2063d0a84f8208a
Successfully built clang wrapt
Installing collected packages: flatbuffers, clang, six, wheel, astunparse, numpy, opt-einsum, cached-property, h5py, keras, typing-extensions, google-pasta, keras-preprocessing, absl-py, grpcio, wrapt, tensorboard-data-server, pyasn1, rsa, pyasn1-modules, cachetools, google-auth, oauthlib, requests-oauthlib, google-auth-oauthlib, tensorboard-plugin-wit, tensorboard, tensorflow-estimator, gast, tensorflow
  WARNING: The script wheel is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  Found existing installation: typing-extensions 3.10.0.2
    Uninstalling typing-extensions-3.10.0.2:
      Successfully uninstalled typing-extensions-3.10.0.2
  WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed absl-py-0.15.0 astunparse-1.6.3 cached-property-1.5.2 cachetools-4.2.4 clang-5.0 flatbuffers-1.12 gast-0.4.0 google-auth-2.3.0 google-auth-oauthlib-0.4.6 google-pasta-0.2.0 grpcio-1.41.0 h5py-3.1.0 keras-2.6.0 keras-preprocessing-1.1.2 numpy-1.19.5 oauthlib-3.1.1 opt-einsum-3.3.0 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.0 rsa-4.7.2 six-1.15.0 tensorboard-2.7.0 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.0 tensorflow-2.6.0 tensorflow-estimator-2.6.0 typing-extensions-3.7.4.3 wheel-0.37.0 wrapt-1.12.1
In [ ]:
# obsolete: original
# The new version of dataset is only available in the tfds-nightly package.
#%pip --no-cache-dir install tensorflow-datasets --user
# DON'T MISS TO RESTART THE KERNEL
In [ ]:
#pip install tensorflow_datasets
In [1]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
In [2]:
# TODO: Make all other necessary imports.
import warnings
warnings.filterwarnings('ignore')

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import time
import numpy as np
import matplotlib.pyplot as plt

import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
tfds.disable_progress_bar()

import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
In [3]:
from workspace_utils import active_session

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [4]:
# Download data to default local directory "~/tensorflow_datasets"
!python -m tensorflow_datasets.scripts.download_and_prepare --register_checksums=True --datasets=oxford_flowers102

# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()
dataset, dataset_info = tfds.load('oxford_flowers102', as_supervised=True, with_info=True)

# TODO: Create a training set, a validation set and a test set.
train_set = dataset['train']
test_set = dataset['test']
val_set = dataset['validation']
2021-10-24 09:59:41.999785: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory
2021-10-24 09:59:41.999984: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
  File "/opt/conda/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/opt/conda/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/root/.local/lib/python3.7/site-packages/tensorflow_datasets/scripts/download_and_prepare.py", line 25, in <module>
    from tensorflow_datasets.scripts.cli import main as main_cli
  File "/root/.local/lib/python3.7/site-packages/tensorflow_datasets/scripts/cli/main.py", line 40, in <module>
    from tensorflow_datasets.scripts.utils import flag_utils
ModuleNotFoundError: No module named 'tensorflow_datasets.scripts.utils'
Downloading and preparing dataset 328.90 MiB (download: 328.90 MiB, generated: 331.34 MiB, total: 660.25 MiB) to /root/tensorflow_datasets/oxford_flowers102/2.1.1...
Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/2.1.1. Subsequent calls will reuse this data.
In [5]:
dataset_info
Out[5]:
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    full_name='oxford_flowers102/2.1.1',
    description="""
    The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
    in the United Kingdom. Each class consists of between 40 and 258 images. The images have
    large scale, pose and light variations. In addition, there are categories that have large
    variations within the category and several very similar categories.
    
    The dataset is divided into a training set, a validation set and a test set.
    The training set and validation set each consist of 10 images per class (totalling 1020 images each).
    The test set consists of the remaining 6149 images (minimum 20 per class).
    
    Note: The dataset by default comes with a test size larger than the train
    size. For more info see this [issue](https://github.com/tensorflow/datasets/issues/3022).
    """,
    homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
    data_path='/root/tensorflow_datasets/oxford_flowers102/2.1.1',
    download_size=328.90 MiB,
    dataset_size=331.34 MiB,
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
    }),
    supervised_keys=('image', 'label'),
    disable_shuffling=False,
    splits={
        'test': <SplitInfo num_examples=6149, num_shards=2>,
        'train': <SplitInfo num_examples=1020, num_shards=1>,
        'validation': <SplitInfo num_examples=1020, num_shards=1>,
    },
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
)
In [6]:
dataset_info.features['image']
Out[6]:
Image(shape=(None, None, 3), dtype=tf.uint8)
In [7]:
num_classes = dataset_info.features['label'].num_classes
print(num_classes)
102
In [8]:
dataset_info.splits['train']
Out[8]:
<SplitInfo num_examples=1020, num_shards=1>
In [9]:
dataset_info.splits['validation']
Out[9]:
<SplitInfo num_examples=1020, num_shards=1>
In [10]:
dataset_info.splits['test']
Out[10]:
<SplitInfo num_examples=6149, num_shards=2>

Explore the Dataset

In [11]:
# TODO: Get the number of examples in each set from the dataset info.
num_training_examples = dataset_info.splits['train'].num_examples
num_validation_examples = dataset_info.splits['validation'].num_examples
num_test_examples = dataset_info.splits['test'].num_examples

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes

print('Number of train samples:', num_training_examples)
print('Number of validation samples:', num_validation_examples)
print('Number of test samples:', num_test_examples)
print('Number of label classes:', num_classes)
Number of train samples: 1020
Number of validation samples: 1020
Number of test samples: 6149
Number of label classes: 102
In [12]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for oneimage, label in train_set.take(3):
    print('Shape of image: {0} , label value of image: {1}'.format(oneimage.shape, label.numpy()))
Shape of image: (500, 667, 3) , label value of image: 72
Shape of image: (500, 666, 3) , label value of image: 84
Shape of image: (670, 500, 3) , label value of image: 70
In [13]:
# TODO: Plot 1 image from the training set. 
# Set the title of the plot to the corresponding image label. 
for image, label in train_set.take(1):
    image = image.numpy()
    label = label.numpy()
    plt.title(label)
    plt.imshow(image)
    plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [14]:
import json
with open('label_map.json', 'r') as f:
    class_names = json.load(f)

print('class_names Datatpye: ', type(class_names))

for key in sorted(class_names.keys()):
    print(key, ' : ', class_names[key])
class_names Datatpye:  <class 'dict'>
1  :  pink primrose
10  :  globe thistle
100  :  blanket flower
101  :  trumpet creeper
102  :  blackberry lily
11  :  snapdragon
12  :  colt's foot
13  :  king protea
14  :  spear thistle
15  :  yellow iris
16  :  globe-flower
17  :  purple coneflower
18  :  peruvian lily
19  :  balloon flower
2  :  hard-leaved pocket orchid
20  :  giant white arum lily
21  :  fire lily
22  :  pincushion flower
23  :  fritillary
24  :  red ginger
25  :  grape hyacinth
26  :  corn poppy
27  :  prince of wales feathers
28  :  stemless gentian
29  :  artichoke
3  :  canterbury bells
30  :  sweet william
31  :  carnation
32  :  garden phlox
33  :  love in the mist
34  :  mexican aster
35  :  alpine sea holly
36  :  ruby-lipped cattleya
37  :  cape flower
38  :  great masterwort
39  :  siam tulip
4  :  sweet pea
40  :  lenten rose
41  :  barbeton daisy
42  :  daffodil
43  :  sword lily
44  :  poinsettia
45  :  bolero deep blue
46  :  wallflower
47  :  marigold
48  :  buttercup
49  :  oxeye daisy
5  :  english marigold
50  :  common dandelion
51  :  petunia
52  :  wild pansy
53  :  primula
54  :  sunflower
55  :  pelargonium
56  :  bishop of llandaff
57  :  gaura
58  :  geranium
59  :  orange dahlia
6  :  tiger lily
60  :  pink-yellow dahlia
61  :  cautleya spicata
62  :  japanese anemone
63  :  black-eyed susan
64  :  silverbush
65  :  californian poppy
66  :  osteospermum
67  :  spring crocus
68  :  bearded iris
69  :  windflower
7  :  moon orchid
70  :  tree poppy
71  :  gazania
72  :  azalea
73  :  water lily
74  :  rose
75  :  thorn apple
76  :  morning glory
77  :  passion flower
78  :  lotus lotus
79  :  toad lily
8  :  bird of paradise
80  :  anthurium
81  :  frangipani
82  :  clematis
83  :  hibiscus
84  :  columbine
85  :  desert-rose
86  :  tree mallow
87  :  magnolia
88  :  cyclamen
89  :  watercress
9  :  monkshood
90  :  canna lily
91  :  hippeastrum
92  :  bee balm
93  :  ball moss
94  :  foxglove
95  :  bougainvillea
96  :  camellia
97  :  mallow
98  :  mexican petunia
99  :  bromelia
In [15]:
for image, label in train_set.take(1):
    ymin = label.numpy()

print(ymin)

ymax=ymin
i=0
for image, label in train_set:
    i+=1
    ymin = min(label.numpy(), ymin)
    ymax = max(label.numpy(), ymax)

for image, label in val_set:
    i+=1
    ymin = min(label.numpy(), ymin)
    ymax = max(label.numpy(), ymax)    
    
for image, label in test_set:
    i+=1
    ymin = min(label.numpy(), ymin)
    ymax = max(label.numpy(), ymax)
    
print('ymin: ', ymin)
print('ymin: ', ymax)
print('Diff Iterations and total Samples:', i - (num_training_examples + num_validation_examples +num_test_examples))
72
ymin:  0
ymin:  101
Diff Iterations and total Samples: 0

Label Index shift necessary as dictionary has one-based index!

In [16]:
class_names_new = dict()
for key in sorted(class_names.keys()):
    oldindexint = int(key)
    class_names_new[str(oldindexint-1)] = class_names[key]
In [17]:
for key in sorted(class_names_new.keys()):
    print(key, ' : ', class_names_new[key])
0  :  pink primrose
1  :  hard-leaved pocket orchid
10  :  snapdragon
100  :  trumpet creeper
101  :  blackberry lily
11  :  colt's foot
12  :  king protea
13  :  spear thistle
14  :  yellow iris
15  :  globe-flower
16  :  purple coneflower
17  :  peruvian lily
18  :  balloon flower
19  :  giant white arum lily
2  :  canterbury bells
20  :  fire lily
21  :  pincushion flower
22  :  fritillary
23  :  red ginger
24  :  grape hyacinth
25  :  corn poppy
26  :  prince of wales feathers
27  :  stemless gentian
28  :  artichoke
29  :  sweet william
3  :  sweet pea
30  :  carnation
31  :  garden phlox
32  :  love in the mist
33  :  mexican aster
34  :  alpine sea holly
35  :  ruby-lipped cattleya
36  :  cape flower
37  :  great masterwort
38  :  siam tulip
39  :  lenten rose
4  :  english marigold
40  :  barbeton daisy
41  :  daffodil
42  :  sword lily
43  :  poinsettia
44  :  bolero deep blue
45  :  wallflower
46  :  marigold
47  :  buttercup
48  :  oxeye daisy
49  :  common dandelion
5  :  tiger lily
50  :  petunia
51  :  wild pansy
52  :  primula
53  :  sunflower
54  :  pelargonium
55  :  bishop of llandaff
56  :  gaura
57  :  geranium
58  :  orange dahlia
59  :  pink-yellow dahlia
6  :  moon orchid
60  :  cautleya spicata
61  :  japanese anemone
62  :  black-eyed susan
63  :  silverbush
64  :  californian poppy
65  :  osteospermum
66  :  spring crocus
67  :  bearded iris
68  :  windflower
69  :  tree poppy
7  :  bird of paradise
70  :  gazania
71  :  azalea
72  :  water lily
73  :  rose
74  :  thorn apple
75  :  morning glory
76  :  passion flower
77  :  lotus lotus
78  :  toad lily
79  :  anthurium
8  :  monkshood
80  :  frangipani
81  :  clematis
82  :  hibiscus
83  :  columbine
84  :  desert-rose
85  :  tree mallow
86  :  magnolia
87  :  cyclamen
88  :  watercress
89  :  canna lily
9  :  globe thistle
90  :  hippeastrum
91  :  bee balm
92  :  ball moss
93  :  foxglove
94  :  bougainvillea
95  :  camellia
96  :  mallow
97  :  mexican petunia
98  :  bromelia
99  :  blanket flower
In [18]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
for image, label in train_set.take(1):
    image = image.numpy()
    plt.title(class_names_new[str(label.numpy())])
    plt.imshow(image)
    plt.show()
In [19]:
class_names
Out[19]:
{'21': 'fire lily',
 '3': 'canterbury bells',
 '45': 'bolero deep blue',
 '1': 'pink primrose',
 '34': 'mexican aster',
 '27': 'prince of wales feathers',
 '7': 'moon orchid',
 '16': 'globe-flower',
 '25': 'grape hyacinth',
 '26': 'corn poppy',
 '79': 'toad lily',
 '39': 'siam tulip',
 '24': 'red ginger',
 '67': 'spring crocus',
 '35': 'alpine sea holly',
 '32': 'garden phlox',
 '10': 'globe thistle',
 '6': 'tiger lily',
 '93': 'ball moss',
 '33': 'love in the mist',
 '9': 'monkshood',
 '102': 'blackberry lily',
 '14': 'spear thistle',
 '19': 'balloon flower',
 '100': 'blanket flower',
 '13': 'king protea',
 '49': 'oxeye daisy',
 '15': 'yellow iris',
 '61': 'cautleya spicata',
 '31': 'carnation',
 '64': 'silverbush',
 '68': 'bearded iris',
 '63': 'black-eyed susan',
 '69': 'windflower',
 '62': 'japanese anemone',
 '20': 'giant white arum lily',
 '38': 'great masterwort',
 '4': 'sweet pea',
 '86': 'tree mallow',
 '101': 'trumpet creeper',
 '42': 'daffodil',
 '22': 'pincushion flower',
 '2': 'hard-leaved pocket orchid',
 '54': 'sunflower',
 '66': 'osteospermum',
 '70': 'tree poppy',
 '85': 'desert-rose',
 '99': 'bromelia',
 '87': 'magnolia',
 '5': 'english marigold',
 '92': 'bee balm',
 '28': 'stemless gentian',
 '97': 'mallow',
 '57': 'gaura',
 '40': 'lenten rose',
 '47': 'marigold',
 '59': 'orange dahlia',
 '48': 'buttercup',
 '55': 'pelargonium',
 '36': 'ruby-lipped cattleya',
 '91': 'hippeastrum',
 '29': 'artichoke',
 '71': 'gazania',
 '90': 'canna lily',
 '18': 'peruvian lily',
 '98': 'mexican petunia',
 '8': 'bird of paradise',
 '30': 'sweet william',
 '17': 'purple coneflower',
 '52': 'wild pansy',
 '84': 'columbine',
 '12': "colt's foot",
 '11': 'snapdragon',
 '96': 'camellia',
 '23': 'fritillary',
 '50': 'common dandelion',
 '44': 'poinsettia',
 '53': 'primula',
 '72': 'azalea',
 '65': 'californian poppy',
 '80': 'anthurium',
 '76': 'morning glory',
 '37': 'cape flower',
 '56': 'bishop of llandaff',
 '60': 'pink-yellow dahlia',
 '82': 'clematis',
 '58': 'geranium',
 '75': 'thorn apple',
 '41': 'barbeton daisy',
 '95': 'bougainvillea',
 '43': 'sword lily',
 '83': 'hibiscus',
 '78': 'lotus lotus',
 '88': 'cyclamen',
 '94': 'foxglove',
 '81': 'frangipani',
 '74': 'rose',
 '89': 'watercress',
 '73': 'water lily',
 '46': 'wallflower',
 '77': 'passion flower',
 '51': 'petunia'}

Create Pipeline

In [20]:
# TODO: Create a pipeline for each set.

# - As MobileNet shall be used as convolutional neural networt, image shape has to be adapted to it's size: (224,224,3)
# - normalize the images using format_image()
# - shuffle rate of 25%
# - only shuffle traning set - validation set and test set has no feedback to the nn

batch_size = 32
image_size = 224

def format_image(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (image_size, image_size))
    image /= 255
    return image, label

# augementation of the images
def augement_image(image, label):
    image = tf.image.stateless_random_flip_left_right(image, (1,2))
    image = tf.image.stateless_random_flip_up_down(image, (1,2)),
    image = tf.image.stateless_random_saturation(image, 0.5, 1.0,(1,2)),
    image = tf.image.stateless_random_contrast(image, lower=0.1, upper=1, seed=(1,2)),
    image = tf.image.stateless_random_hue(image, 0.1,(1,2))
    #image = tf.image.central_crop(image, 0.5)
    #image = tf.image.stateless_random_crop(image, 0.8,(1,2))
    return image, label

# from above:
#num_training_examples = dataset_info.splits['train'].num_examples

#train_batches = train_set.shuffle(num_training_examples//4).map(format_image).map(augement_image).batch(batch_size).prefetch(1)
train_batches = train_set.shuffle(num_training_examples//4).map(format_image).batch(batch_size).prefetch(1)
val_batches = val_set.map(format_image).batch(batch_size).prefetch(1)
test_batches = test_set.map(format_image).batch(batch_size).prefetch(1)

Verifiy train_batches picture

In [21]:
for image_batch, label_batch in train_batches.take(1):
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

# Plot the image
plt.imshow(images[0], cmap = plt.cm.binary)
plt.colorbar()

plt.title('Name: '+class_names_new[str(labels[0])]+ '. Label number: '+str(labels[0]))
plt.show()

Verifiy val_batches picture

In [22]:
for image_batch, label_batch in val_batches.take(1):
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

# Plot the image
plt.imshow(images[0], cmap = plt.cm.binary)
plt.colorbar()

plt.title('Name: '+class_names_new[str(labels[0])]+ '. Label number: '+str(labels[0]))
plt.show()

Verifiy test_batches picture

In [23]:
for image_batch, label_batch in test_batches.take(1):
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

# Plot the image
plt.imshow(images[0], cmap = plt.cm.binary)
plt.colorbar()

plt.title('Name: '+class_names_new[str(labels[0])]+ '. Label number: '+str(labels[0]))
plt.show()

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [24]:
# TODO: Build and train your network.
In [54]:
tf.keras.backend.clear_session()
In [55]:
# Import pre-trained network
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

feature_extractor = hub.KerasLayer(URL, input_shape=(image_size, image_size,3))

# Do not modify the weights from predefined nn
feature_extractor.trainable = False
In [56]:
type(feature_extractor)
Out[56]:
tensorflow_hub.keras_layer.KerasLayer

Documentation of models

ToDo number of labels = num_classes = 102

model_v1:

paramters:
- Epochs = 80
- l1 regularization
- 2 hidden layers
    - h1: 500 units, dropout: 0.2
    - h2: 500 units, dropout: 0.2

model v1

modelpara_EPOCHS = 80 modelpara_h1_numunits = 500 modelpara_h2_numunits = 500 modelpara_h1_dropout = 0.2 modelpara_h2_dropout = 0.2

model v2

modelpara_EPOCHS = 70 modelpara_h1_numunits = 1028 modelpara_h1_dropout = 0.2

model v3

modelpara_EPOCHS = 20 modelpara_h1_numunits = 512 modelpara_h2_numunits = 512 modelpara_h1_dropout = 0.2 modelpara_h2_dropout = 0.2

In [57]:
# model v4
modelpara_EPOCHS = 20
modelpara_h1_numunits = 1028
modelpara_h2_numunits = 1028
modelpara_h1_dropout = 0.25
modelpara_h2_dropout = 0.25
In [ ]:
# not yet tried
# model v5

#Optimizer 
#adam for sgd

# Parameter
#modelpara_EPOCHS = 35
#modelpara_h1_numunits = 1028
#modelpara_h2_numunits = 1028
#modelpara_h3_numunits = 512
#modelpara_h1_dropout = 0.3
#modelpara_h2_dropout = 0.3
#modelpara_h3_dropout = 0.2

Beste Variante

model v4

modelpara_EPOCHS = 20 modelpara_h1_numunits = 1028 modelpara_h2_numunits = 1028 modelpara_h1_dropout = 0.25 modelpara_h2_dropout = 0.25

Build model

Build model

model = tf.keras.Sequential([ feature_extractor, tf.keras.layers.Dense(modelpara_h1_numunits, activation = 'relu', kernel_regularizer='l2'), BatchNormalization(), tf.keras.layers.Dropout(modelpara_h1_dropout), tf.keras.layers.Dense(modelpara_h2_numunits, activation = 'relu', kernel_regularizer='l2'), BatchNormalization(), tf.keras.layers.Dropout(modelpara_h2_dropout), tf.keras.layers.Dense(num_classes, activation = 'softmax') ])

Compile the model

model.compile(optimizer='sgd', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

In [58]:
def scheduler(epoch, lr):
  if epoch < modelpara_EPOCHS/2:
    return lr
  else:
    return lr * tf.math.exp(-0.1)
In [59]:
#import BatchNormalization
from tensorflow.keras.layers import Dense, BatchNormalization

# Build model
model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dense(modelpara_h1_numunits, activation = 'relu', kernel_regularizer='l2'),
        BatchNormalization(),
        tf.keras.layers.Dropout(modelpara_h1_dropout),
        tf.keras.layers.Dense(modelpara_h2_numunits, activation = 'relu', kernel_regularizer='l2'),
        BatchNormalization(),
        tf.keras.layers.Dropout(modelpara_h2_dropout),
        tf.keras.layers.Dense(num_classes, activation = 'softmax')
])

# Compile the model
model.compile(optimizer='sgd',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# Stop training when loss is invariant for 5 epochs
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)

lrscheduler = tf.keras.callbacks.LearningRateScheduler(scheduler)

# Save the Model with the lowest validation loss
save_best = tf.keras.callbacks.ModelCheckpoint('./model_v1_2410_1.h5',
                                               monitor='val_loss',
                                               save_best_only=True)

# plot model configuration
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense (Dense)                (None, 1028)              1316868   
_________________________________________________________________
batch_normalization (BatchNo (None, 1028)              4112      
_________________________________________________________________
dropout (Dropout)            (None, 1028)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 1028)              1057812   
_________________________________________________________________
batch_normalization_1 (Batch (None, 1028)              4112      
_________________________________________________________________
dropout_1 (Dropout)          (None, 1028)              0         
_________________________________________________________________
dense_2 (Dense)              (None, 102)               104958    
=================================================================
Total params: 4,745,846
Trainable params: 2,483,750
Non-trainable params: 2,262,096
_________________________________________________________________
In [60]:
# train the model
# test with one epoch
EPOCHS = modelpara_EPOCHS
history = model.fit(train_batches,
                    epochs = EPOCHS,
                    validation_data=val_batches,
                    callbacks=[early_stopping, save_best, lrscheduler])
Epoch 1/20
32/32 [==============================] - 87s 3s/step - loss: 26.4002 - accuracy: 0.0618 - val_loss: 25.5308 - val_accuracy: 0.1912
Epoch 2/20
32/32 [==============================] - 82s 3s/step - loss: 23.7401 - accuracy: 0.4333 - val_loss: 24.6647 - val_accuracy: 0.4392
Epoch 3/20
32/32 [==============================] - 79s 2s/step - loss: 22.3940 - accuracy: 0.7108 - val_loss: 23.8945 - val_accuracy: 0.5706
Epoch 4/20
32/32 [==============================] - 79s 2s/step - loss: 21.6578 - accuracy: 0.8265 - val_loss: 23.2005 - val_accuracy: 0.6304
Epoch 5/20
32/32 [==============================] - 79s 2s/step - loss: 21.0964 - accuracy: 0.9098 - val_loss: 22.5874 - val_accuracy: 0.6696
Epoch 6/20
32/32 [==============================] - 80s 3s/step - loss: 20.6638 - accuracy: 0.9520 - val_loss: 22.0370 - val_accuracy: 0.6951
Epoch 7/20
32/32 [==============================] - 80s 3s/step - loss: 20.3018 - accuracy: 0.9765 - val_loss: 21.5565 - val_accuracy: 0.7127
Epoch 8/20
32/32 [==============================] - 82s 3s/step - loss: 19.9924 - accuracy: 0.9755 - val_loss: 21.1349 - val_accuracy: 0.7176
Epoch 9/20
32/32 [==============================] - 83s 3s/step - loss: 19.7076 - accuracy: 0.9843 - val_loss: 20.7611 - val_accuracy: 0.7206
Epoch 10/20
32/32 [==============================] - 82s 3s/step - loss: 19.4060 - accuracy: 0.9931 - val_loss: 20.4217 - val_accuracy: 0.7294
Epoch 11/20
32/32 [==============================] - 86s 3s/step - loss: 19.1670 - accuracy: 0.9931 - val_loss: 20.1365 - val_accuracy: 0.7314
Epoch 12/20
32/32 [==============================] - 80s 2s/step - loss: 18.9321 - accuracy: 0.9931 - val_loss: 19.8838 - val_accuracy: 0.7471
Epoch 13/20
32/32 [==============================] - 78s 2s/step - loss: 18.7395 - accuracy: 0.9941 - val_loss: 19.6656 - val_accuracy: 0.7441
Epoch 14/20
32/32 [==============================] - 78s 2s/step - loss: 18.5570 - accuracy: 0.9990 - val_loss: 19.4787 - val_accuracy: 0.7392
Epoch 15/20
32/32 [==============================] - 78s 2s/step - loss: 18.3946 - accuracy: 0.9990 - val_loss: 19.3123 - val_accuracy: 0.7461
Epoch 16/20
32/32 [==============================] - 80s 3s/step - loss: 18.2620 - accuracy: 0.9980 - val_loss: 19.1662 - val_accuracy: 0.7480
Epoch 17/20
32/32 [==============================] - 82s 3s/step - loss: 18.1318 - accuracy: 0.9980 - val_loss: 19.0401 - val_accuracy: 0.7500
Epoch 18/20
32/32 [==============================] - 79s 2s/step - loss: 18.0244 - accuracy: 0.9971 - val_loss: 18.9278 - val_accuracy: 0.7480
Epoch 19/20
32/32 [==============================] - 85s 3s/step - loss: 17.9166 - accuracy: 0.9980 - val_loss: 18.8239 - val_accuracy: 0.7422
Epoch 20/20
32/32 [==============================] - 87s 3s/step - loss: 17.8277 - accuracy: 1.0000 - val_loss: 18.7339 - val_accuracy: 0.7461

Check GPU state

In [31]:
#print('Is there a GPU Available:', tf.test.is_gpu_available())
Is there a GPU Available: False
In [ ]:
# Not necessary: Run training iteration with GPU

#from workspace_utils import active_session

#EPOCHS = modelpara_EPOCHS
#with active_session():
    # train the model
#    history = model.fit(train_batches,
#                    epochs = EPOCHS,
#                    validation_data=val_batches,
#                    callbacks=[early_stopping, save_best, lrscheduler]) 
In [35]:
# save the trained model
#model.save('./model_v1_2410_1_epochs_1.h5', overwrite=True)
In [62]:
# load the trained model
#model=tf.keras.models.load_model('./model_v1_parttrained.h5', custom_objects={'KerasLayer':hub.KerasLayer})
#model_untrained = tf.keras.models.load_model('./model_v1_parttrained.h5')

model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense (Dense)                (None, 1028)              1316868   
_________________________________________________________________
batch_normalization (BatchNo (None, 1028)              4112      
_________________________________________________________________
dropout (Dropout)            (None, 1028)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 1028)              1057812   
_________________________________________________________________
batch_normalization_1 (Batch (None, 1028)              4112      
_________________________________________________________________
dropout_1 (Dropout)          (None, 1028)              0         
_________________________________________________________________
dense_2 (Dense)              (None, 102)               104958    
=================================================================
Total params: 4,745,846
Trainable params: 2,483,750
Non-trainable params: 2,262,096
_________________________________________________________________

Values of accuracy and loss for training set

In [63]:
# TODO: Plot the loss and accuracy values achieved during training for the training set.
loss, accuracy = model.evaluate(train_batches)
print('\nLoss on the training set: {:,.3f}'.format(loss))
print('Accuracy on the training set: {:.3%}'.format(accuracy))
32/32 [==============================] - 40s 1s/step - loss: 17.7283 - accuracy: 1.0000

Loss on the training set: 17.728
Accuracy on the training set: 100.000%

Values of accuracy and loss for validation set

In [64]:
# TODO: Plot the loss and accuracy values achieved during training for the validation set.
loss, accuracy = model.evaluate(val_batches)
print('\nLoss on the validation set: {:,.3f}'.format(loss))
print('Accuracy on the validation set: {:.3%}'.format(accuracy))
32/32 [==============================] - 40s 1s/step - loss: 18.7339 - accuracy: 0.7461

Loss on the validation set: 18.734
Accuracy on the validation set: 74.608%

Plot of accuracies for training and validation set

In [68]:
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(EPOCHS)

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [65]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(test_batches)
print('\nLoss on the validation set: {:,.3f}'.format(loss))
print('Accuracy on the validation set: {:.3%}'.format(accuracy))
193/193 [==============================] - 241s 1s/step - loss: 18.8882 - accuracy: 0.7200

Loss on the validation set: 18.888
Accuracy on the validation set: 71.995%
In [66]:
print('\nLoss on the test set: {:,.3f}'.format(loss))
print('Accuracy on the test set: {:.3%}'.format(accuracy))
Loss on the test set: 18.888
Accuracy on the test set: 71.995%

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [ ]:
# TODO: Save your trained model as a Keras model.
# save the trained model
model.save('./model_best_v4.h5', overwrite=True)

Load the Keras Model

Load the Keras model you saved above.

In [70]:
# TODO: Load the Keras model
model=tf.keras.models.load_model('./model_best_v4.h5', custom_objects={'KerasLayer':hub.KerasLayer})
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
keras_layer (KerasLayer)     (None, 1280)              2257984   
_________________________________________________________________
dense (Dense)                (None, 1028)              1316868   
_________________________________________________________________
batch_normalization (BatchNo (None, 1028)              4112      
_________________________________________________________________
dropout (Dropout)            (None, 1028)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 1028)              1057812   
_________________________________________________________________
batch_normalization_1 (Batch (None, 1028)              4112      
_________________________________________________________________
dropout_1 (Dropout)          (None, 1028)              0         
_________________________________________________________________
dense_2 (Dense)              (None, 102)               104958    
=================================================================
Total params: 4,745,846
Trainable params: 2,483,750
Non-trainable params: 2,262,096
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [124]:
# TODO: Create the process_image function
def process_image(npimage):
    tfimage = tf.convert_to_tensor(npimage)
    image_size = 224
    tfimageresized = tf.image.resize(tfimage, (image_size, image_size))
    tfimageresized /= 255
    npimageout =tfimageresized.numpy()
    #print(npimageout.shape)
    return npimageout

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [125]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [126]:
# TODO: Create the predict function
def predict(image_path, model, top_k):
    from PIL import Image
    import operator

    imagejpg = Image.open(image_path)
    npimage = np.asarray(imagejpg)

    npimage_rez = process_image(npimage)
    npimage_rez_formodel = np.expand_dims(npimage_rez,0)
    tfimage_rez_formodel=tf.convert_to_tensor(npimage_rez_formodel)
    praed = model.predict(tfimage_rez_formodel)
    pylist = praed[0].tolist()
    pdict = dict(zip(list(range(102)),pylist))
    sortedDict = sorted(pdict.items(), key=operator.itemgetter(1), reverse=True)
    probs=[]
    classes=[]
    for i in range(top_k):
        probs.append(sortedDict[i][1])
        classes.append(sortedDict[i][0])
    
    return probs, classes

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [143]:
# TODO: Plot the input image along with the top 5 classes
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
probs, classes = predict(image_path, model, 5)
print('probs:', probs)
print('classes: ', classes)
probs: [0.9968428611755371, 0.0002685404324438423, 0.00020891462918370962, 0.00020148629846516997, 0.00018386293959338218]
classes:  [1, 19, 5, 39, 67]
In [165]:
# Plot the following flowers
flowername1 = 'cautleya_spicata'
flowername2 = 'hard-leaved_pocket_orchid'
flowername3 = 'orange_dahlia'
flowername4 = 'wild_pansy'
In [1]:
def printimageclassification(flowername):
    
    from PIL import Image
    image_path = './test_images/'+ flowername + '.jpg'
    im = Image.open(image_path)
    top_k=5
    probs, classes = predict(image_path, model, top_k) 
    strlist=[class_names_new[str(i)] for i in classes]
    fig, (ax1, ax2) = plt.subplots(figsize=(9,11), ncols=2)
    ax1.set_title(flowername)
    ax1.imshow(im, cmap = plt.cm.binary)
    ax1.axis('off')
    ax2.barh(np.arange(top_k),probs)
    ax2.set_aspect(0.1)
    ax2.set_yticks(np.arange(top_k))
    ax2.set_yticklabels(strlist)
    ax2.set_title('Class Probability')
    ax2.set_xlim(0, 1.1)
    plt.tight_layout()
In [167]:
printimageclassification(flowername1)
In [168]:
printimageclassification(flowername2)
In [169]:
printimageclassification(flowername3)
In [170]:
printimageclassification(flowername4)